const user = require('../model/User');
const encrypt = require('../../utils/encryptUtil');
const config = require('../../config/config');
const ServerError = require('../../utils/ServerError');

module.exports = {
    loadUser: async (username, password) => {
        let dbUser = await user.loadUser(username);
        if (dbUser && dbUser.length == 1 && dbUser[0].password === encrypt.encrypt(password, config.PWD_SALT)) {
            await user.loginSuccess(username);
            return dbUser[0];
        }
        return null;
    },

    findUser: async (username) => {
        let dbUser = await user.loadUser(username);
        if (dbUser && dbUser.length == 1) {
            return dbUser[0];
        }
        return null;
    },

    getUserList: async (index = 0, limit = 10) => {
        let usr_count = await user.getUserCount();

        if (usr_count < index * limit) {
            throw new ServerError(ServerError.CODE.ILLEGAL_PARAMS);
        }

        if (usr_count > 0) {
            let usr_list = await user.getUserList(index, limit);
            usr_list.forEach(usr => {
                usr.password = '';
            });
            return {total: usr_count, list: usr_list}
        }

        return {total: 0};
    },

    addUser: async (params) => {
        params.password = encrypt.encrypt(params.password, config.PWD_SALT);
        return await user.addUser(params);
    },

    updateUser: async (params) => {
        return await user.updateUser(params);
    },

    changePassword: async (username, password) => {
        return await user.changePassword(username, encrypt.encrypt(password, config.PWD_SALT));
    },

    deleteUser: async (username, admin_id) => {
        return await  user.deleteUser(username, admin_id);
    },

    changeAvatar: async (username, img_url) => {
        return await user.changeAvatar(username, img_url);
    }

}
